<?php  
/** 
 * ImageBehavior - To help with image CRUD 
 * @author Grzegorz Pawlik 1.0 
 * @author Travis Rowland (Theaxiom) 1.2 
 * @version 1.2 
 */ 
class ImageBehavior extends ModelBehavior { 
     
    var $_defaults = array( 
        'cache_dir' => 'filecache', 
        'use_cache' => true, 
        'file_input' => 'File', 
        'tmp_name' => 'tmp_name', 
        'model_name' => 'Image', 
        'file' => 'file',
        'ext_field' => 'ext', 
        'filehash_field' => 'filehash', 
        'name_field' => 'name', 
        'data_field' => 'data', 
        'clean_name_field' => 'clean_name'
        //TODO: Parametro para redimensionar imagem antes de salvar
    ); 
     
    function setup(&$Model, $config = array()) { 
        if (!is_array($config)) { 
            $config = array('type' => $config); 
        } 
        $settings = array_merge($this->_defaults, $config); 
        $this->settings[$Model->alias] = $settings; 
    } 

    function beforeValidate(&$Model) { 
        extract($this->settings[$Model->alias]);
        if(isset($Model->data[$Model->alias][$file_input][$tmp_name]) && is_uploaded_file($Model->data[$Model->alias][$file_input][$tmp_name])) { 
            $Model->data[$Model->alias] = array_merge($Model->data[$Model->alias],  $Model->data[$Model->alias][$file_input]); 
            //App::import('Core', 'File');
            App::uses('File', 'Utility');
            $file = new File($Model->data[$Model->alias][$tmp_name], false); 
            $Model->data[$Model->alias][$data_field] = addslashes( $file->read() ); 
            $Model->data[$Model->alias][$filehash_field] = md5($Model->data[$Model->alias][$name_field] . $Model->data[$Model->alias][$data_field]); 
            $file = explode('.', $Model->data[$Model->alias][$name_field]); 
            $Model->data[$Model->alias][$ext_field] = array_pop($file); 
            $Model->data[$Model->alias][$clean_name_field] = array_pop($file); 
        } 
         
        return true; 
    } 

    function afterFind(&$Model, $results, $primary) { 
        extract($this->settings[$Model->alias]); 
         
        foreach($results as $key => $val) { 
            if (isset($val[$model_name])) { 
                $relpath = $cache_dir . '/' . $val[$model_name][$filehash_field] . '.' . $val[$model_name][$ext_field]; 
                $fullpath = IMAGES . $relpath; 
                 
                if(!file_exists($fullpath) || !$use_cache) { 
                    file_put_contents($fullpath, stripslashes($results[$key][$model_name][$data_field]));
                } 
                 
                $results[$key][$model_name][$file] = $relpath; 
                unset($results[$key][$model_name][$data_field]); 
            } 
        } 

        return $results; 
    } 
} 
?>